package com.framework.bdf4j.comm.download;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @describle xlsx的下载器
 * @warning 该程序依赖 apache.pio
 */
@Slf4j
public class LocalFileDownLoader implements DownLoader {

    /**
     *  每种方式的下载交由各个实现自己去填充，包括对返回头的设置
     * @param fileName 文件名
     * @param request  http请求对象
     * @param response http响应对象
     */
    @Override
    public void download(String fileName, HttpServletRequest request,HttpServletResponse response) throws IOException {

        //获取设置response对象
        DownLoadResponseSetting downLoadResponseSetting = DownLoadResponseSetting.getInstance();

        //由于Spring boot 打成jar后在内部都是虚拟路径,因此不能使用文件的方式获取
        ClassPathResource classPathResource = new ClassPathResource("static/file/" + fileName);

        downLoadResponseSetting.convertServlet(request,response,fileName);

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = classPathResource.getInputStream();
            outputStream = response.getOutputStream();
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
        }catch (IOException ex) {
            throw ex;
        }finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
    }
}
